package tech.mhuang.pacebox.sms.bdyun;

import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.sms.SmsClient;
import com.baidubce.services.sms.SmsClientConfiguration;
import com.baidubce.services.sms.model.SendMessageV3Request;
import com.baidubce.services.sms.model.SendMessageV3Response;
import tech.mhuang.pacebox.sms.BaseSmsHandler;
import tech.mhuang.pacebox.sms.SmsFieldProperties;
import tech.mhuang.pacebox.sms.domain.SmsSendRequest;
import tech.mhuang.pacebox.sms.domain.SmsSendResult;

import java.util.Map;

/**
 * 百度云短信
 *
 * @author mhuang
 * @since 1.0.0
 */
public class BdyunSmsHandler implements BaseSmsHandler {

    private SmsFieldProperties properties;
    private SmsClient smsClient;

    @Override
    public void setFieldProperties(SmsFieldProperties properties) {
        this.properties = properties;
        SmsClientConfiguration config = new SmsClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(properties.getAccessKey(), properties.getAccessSecret()));
        config.setEndpoint(properties.getRegion());
        if (properties.isUseProxy()) {
            config.setProxyHost(properties.getProxyHost());
            config.setProxyPort(properties.getProxyPort());
        }
        // 实例化发送客户端
        this.smsClient = new SmsClient(config);
    }

    @Override
    public SmsSendResult send(SmsSendRequest smsSendRequest) {
        SmsSendResult smsResult = SmsSendResult.builder().extendParam(smsSendRequest.getExtendParam()).build();
        SendMessageV3Request request = new SendMessageV3Request();
        request.setTemplate(smsSendRequest.getTemplateCode());
        request.setMobile(smsSendRequest.getMobile());
        request.setContentVar((Map) smsSendRequest.getTemplateParam());
        request.setSignatureId(smsSendRequest.getSign());
        SendMessageV3Response response = smsClient.sendMessage(request);
        smsResult.setMessage(response.getMessage());
        smsResult.setSuccess(response.isSuccess());
        smsResult.setRequestId(response.getRequestId());
        return smsResult;
    }
}
